#include <stdio.h>
#include <stdlib.h>
#include "../utils/topo.h"

/*---------- 示例使用 ----------*/
typedef struct {
    char* name;
    int id;
} Task;

unsigned int taskHash(DataType data) {
    Task* t = (Task*)data;
    return t->id * 31;
}

int taskCompare(DataType a, DataType b) {
    Task* t1 = (Task*)a;
    Task* t2 = (Task*)b;
    return t1->id == t2->id;
}

void printTask(DataType data) {
    Task* t = (Task*)data;
    printf("%s(id:%d)", t->name, t->id);
}

int main() {
    // 创建测试任务
    Task tasks[] = {
        {"Initialize", 1},
        {"LoadConfig", 2},
        {"ConnectDB", 3},
        {"StartService", 4},
        {"RunTests", 5},
        {"Stopped",6}
    };

    // 创建图结构
    Graph* graph = createGraph(10, taskHash, taskCompare);
    for (int i = 0; i < 6; i++) {
        addNode(graph, &tasks[i]);
    }

    // 添加依赖关系
    addEdge(graph, &tasks[0], &tasks[1]); // 1->2
    addEdge(graph, &tasks[0], &tasks[2]); // 1->3
    addEdge(graph, &tasks[1], &tasks[3]); // 2->4
    addEdge(graph, &tasks[2], &tasks[3]); // 3->4
    addEdge(graph, &tasks[3], &tasks[4]); // 4->5
    addEdge(graph, &tasks[3], &tasks[5]); // 4->6
    addEdge(graph, &tasks[4], &tasks[5]); // 5->6
    // 执行拓扑排序
    TopoResult result = {NULL,NULL,0,0};
    //topologicalSortWithBatches(graph,&result);
    topologicalSortWithBatches(graph,&result);
    freeGraph(graph, NULL);
    // 输出结果
    if (result.size == 0) {
        printf("图中存在环路！\n");
    } else {
        printf("拓扑排序结果（总批次：%d）:\n", result.totalBatches);
        for (size_t i = 0; i < result.size; i++) {
            printTask(result.order[i]);
            printf(" -> 批次 %d\n", result.batches[i]);
        }
        free(result.order);
        free(result.batches);
    }

    // freeGraph(graph, NULL);
    return 0;
}
